import { AlertController, ModalController } from '@ionic/angular';
import { Component, Input, OnInit } from '@angular/core';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { VideoImgPopupComponent } from '../video-img-popup/video-img-popup.component';
import { EventService } from 'src/app/shared/service/event.service';
@Component({
  selector: 'app-dynamic-details',
  templateUrl: './dynamic-details.component.html',
  styleUrls: ['./dynamic-details.component.scss'],
})
export class DynamicDetailsComponent implements OnInit {
  @Input() tagData: any = {};
  showLoadMore = false;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  // 筛选及页面数据参数
  params: any = { content: {} };
  sendLabelValue: any;
  noShowFootBtn = true;
  timer: any;
  phoneArray: any;
  constructor(
    private pageModalService: PageModalService,
    private appGlobalService: AppGlobalService,
    public alertController: AlertController,
    private httpService: HttpService,
    public modalController: ModalController,
    public eventService: EventService,
  ) { }

  ngOnInit() {
    this.pageTotal = this.tagData.pageTotal;
    this.pageNo = this.tagData.pageNo;
    this.pageSize = this.tagData.pageSize;
    this.params.content = this.tagData.data.submit;
    this.params.sessionId = localStorage.getItem("sessionId");
    // tslint:disable-next-line: max-line-length
    this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize));

    this.tagData.data.data.forEach(element => {
      if (element.firstRowLeft && element.firstRowLeft.secondText && element.firstRowLeft.secondText.subSecondData) {
        const subSecondDataSlice = element.firstRowLeft.secondText.subSecondData;
        element.firstRowLeft.secondText.showReplies = `展开${subSecondDataSlice.length}条回复`;
        element.firstRowLeft.secondText.subSecondDataSlice = subSecondDataSlice.slice(0, 2);
      }
    });

    if (this.tagData.data.data.length > 0) {
      this.appGlobalService.dynamicDetailsData = this.tagData.data.data[0];
    }

    if (this.eventService.eventEmit.listenerCount('dynamicDetails_dataItem') > 0) {
      this.eventService.eventEmit.removeListener('dynamicDetails_dataItem');
    }
    this.eventService.eventEmit.on("dynamicDetails_dataItem", res => {
      this.tagData.data.data.push(res);
    });

  }

  loadMoreData(event) {
    try {
      this.params = { content: {} };
      this.params = this.tagData.data.submit;
      this.pageNo = this.pageNo + 1;
      // // 参数
      this.params.content.pageNo = this.pageNo;
      this.params.id = this.tagData.data.submit.id;
      this.params.sessionId = localStorage.getItem("sessionId");
      // 请求获取新数据
      this.httpService.post('application/submit', this.params, res => {

        // 请求数据成功
        if (res.success) {
          if (res.data.submit) {
            this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
          }
          const resList = res.data.data;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(v => {
              this.tagData.data.data.push(v);
            });
          } else {
            event.target.disabled = true;
            this.showLoadMore = false;
          }
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          // this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
        event.target.complete();

      }, err => {
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
        event.target.complete();

      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }

  showAll(item) {
    item.show = !item.show;
    if (item.show) {
      item.showText = '收起';
    } else {
      item.showText = '查看全部';
    }
  }

  openImg(imgs, i) {
    this.pageModalService.openImage_url(i, imgs);
  }

  async popup(data) {
    const modal = await this.modalController.create({
      component: VideoImgPopupComponent,
      componentProps: { tagData: data, style: this.tagData.style }
    });
    return await modal.present();

  }

  careBtn(item) {
    const params = {
      content: item.submit.content,
      id: item.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        if (res.data && res.data.eventResult !== undefined && res.data.eventResult === 'true') {
          item.state = '1';
          item.label = '已关注';
        } else if ( res.data && res.data.eventResult !== undefined && res.data.eventResult === 'false') {
          item.state = '0';
          item.label = '关注';
        }
      }
    });
  }

  openPage(link, e?) {
    if (e) {
      e.stopPropagation();
    }
    if (link) {
      this.pageModalService.openPage(link);
    }
  }

  LookReplies(e, item, i) {
    e.stopPropagation();
    if (item.showReplies !== '收起') {
      item.subSecondDataSlice = item.subSecondData;
      item.showReplies = '收起';
    } else {
      item.showReplies = `展开${item.subSecondData.length}条回复`;
      item.subSecondDataSlice = item.subSecondData.slice(0, 2);
    }

  }

  async btnClick(item, data?, i?, leftItem?) {
    const that = this;
    if (item.type === 'iconDelete') {
      // 删除
      this.deleteItem(item.msg, item, data, i);
    } else if (item.type === 'iconSubmit') {
      // 点赞
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (res.data && res.data.eventResult !== undefined) {
            if (res.data.eventResult === "false") {
              item.icon = 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_1683356627189868ce62f30825acfde3a6b9224a96f8e.png';
              item.value = item.value > 0 ? Number(item.value) - 1 : 0;
            } else if (res.data.eventResult === "true") {
              item.icon = 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_16835103291584a0c8015c6cfed9f472d192d8b6ff42b.png';
              item.value = Number(item.value) + 1;
            }
          }
        }
      });
    } else if (item.type === "iconRemove") {
      // 取消：点击取消，取消不做提示，隐藏该行内容  与删除功能一样的逻辑
      if (item.submit) {
        const params = {
          content: item.submit.content,
          id: item.submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (res.success) {
            data.splice(i, 1);
          }
          this.appGlobalService.showToast(res.message, 1500, 'middle');
        });
      }
    } else if (item.type === "iconSendLabel") {
      // 评论
      await this.openPage(item.link);
      this.appGlobalService.sendLabelMsg = item.submit;

      if (this.eventService.eventEmit.listenerCount('sendLabel') > 0) {
        this.eventService.eventEmit.removeListener('sendLabel');
      }
      this.eventService.eventEmit.on('sendLabel', res => {
        if (!this.tagData.data.data[i].id) { // 动态详情没有配置 id
          const arr = res.split("##$$");
          const obj: any = {};
          obj.name = arr[1];
          obj.img = arr[2];
          obj.value = arr[3];
          obj.label = arr[4];
          leftItem.subSecondDataSlice.push(obj);
        } else {
          const page: any = this.appGlobalService.getCurrentTarget();
          if (page.params) {
          } else {
            page.params = {}
          }
          page.params.id = this.tagData.data.data[i].id;
          this.httpService.post('application/page', page, async res => {
            const tagData = JSON.parse(res.script).views[0].tags;
            tagData.forEach(element => {
              if (element.style === 'dynamicDetailsTag' && element.data && element.data.data[0]) {
                if (that.tagData.data.data[i].id === element.data.data[0].id) {
                  that.tagData.data.data[i] = element.data.data[0];                    
                  if (that.tagData.data.data[i].firstRowLeft && that.tagData.data.data[i].firstRowLeft.secondText && that.tagData.data.data[i].firstRowLeft.secondText.subSecondData) {
                    const subSecondDataSlice = that.tagData.data.data[i].firstRowLeft.secondText.subSecondData;
                    that.tagData.data.data[i].firstRowLeft.secondText.showReplies = `展开${subSecondDataSlice.length}条回复`;
                    that.tagData.data.data[i].firstRowLeft.secondText.subSecondDataSlice = subSecondDataSlice.slice(0, 2);
                  }
                }
              }
            });
          });
        }
      });
    } else if (item.type === 'iconCareBtn') {
      // 点关注按钮
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        if (res.success) {
          if (res.data && res.data.eventResult !== undefined) {
            if (res.data.eventResult === "false") {
              item.label = '关注';
              data.forEach(e => {
                if (e.firstRowRight.singleText &&
                  item.submit.content.interest_user_id === e.firstRowRight.singleText.submit.content.interest_user_id) {
                  e.firstRowRight.singleText.label = '关注';
                }
              });

            } else if (res.data.eventResult === "true") {
              item.label = '已关注';
              data.forEach(e => {
                if (e.firstRowRight.singleText &&
                  item.submit.content.interest_user_id === e.firstRowRight.singleText.submit.content.interest_user_id) {
                  e.firstRowRight.singleText.label = '已关注';
                }
              });
            }
          }
        }
        this.appGlobalService.showToast(res.message, 1500, "middle");
      });
    } else if (item.type === "iconLink") {
      if (item.link.type && item.link.type === 'chat') {//

        if (item.link.params !== undefined && item.link.params.chatId !== undefined) {
          this.httpService.gotoChat(item, item.link.params.chatId);

        } else {
          this.httpService.gotoChat(item);
        }
      } else {
        this.openPage(item.link)
      }
    } else if (item.type === "phone") {
      this.phoneArray = item.phone.split(",");
      this.presentAlertConfirm(Number(this.phoneArray[0]), item.name);
    }
  }

  // 删除
  async deleteItem(msg, item, data, index) {
    const alert = await this.alertController.create({
      header: '',
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            if (item && item.submit) {
              const params = {
                content: item.submit.content,
                id: item.submit.id,
                sessionId: localStorage.getItem("sessionId")
              };
              this.httpService.post("application/submit", params, res => {
                if (res.success) {
                  data.splice(index, 1);
                }
                this.appGlobalService.showToast(res.message, 1500, 'middle');
              });
            }
          }
        }
      ]
    });
    alert.present();
  }

  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }

  del(item, data, index) {
    if (item && item.submit) {
      const params = {
        content: item.submit.content,
        id: item.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        if (res.success) {
          data.splice(index, 1);
        }
        this.appGlobalService.showToast(res.message, 1500, 'middle');
      });
    }
  }
}
